package com.itheima.code;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

class Solution {
     private static final Map<Character, Character> map = new HashMap<Character, Character>() {{
         put('{', '}');
         put('[', ']');
         put('(', ')');
         put('?', '?');
     }};
    public boolean isValid(String s) {
        if (s.length() > 0 && !map.containsKey(s.charAt(0))) return false;
        LinkedList<Character> stack = new LinkedList<Character>() {{
            add('?');
        }};
        for (Character c : s.toCharArray()) {
            if (map.containsKey(c)) stack.addLast(c);
            else if (map.get(stack.removeLast()) != c) return false;
        }
        return stack.size() == 1;
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        String test1 = "()[]{}";
        String test2 = "(]";
        System.out.println("字符串 " + test1 + " 是否有效: " + solution.isValid(test1));
        System.out.println("字符串 " + test2 + " 是否有效: " + solution.isValid(test2));
    }
}
